package com.example.rsa;

import com.nimbusds.jose.KeySourceException;
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSelector;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.JWKSource;
import com.nimbusds.jose.proc.SecurityContext;

import java.util.ArrayList;
import java.util.List;

public class RsaKeyPairJWKSource implements JWKSource<SecurityContext> {

    private final RsaKeyPairRepository keyPairRepository;

    public RsaKeyPairJWKSource(RsaKeyPairRepository keyPairRepository) {
        this.keyPairRepository = keyPairRepository;
    }

    @Override
    public List<JWK> get(JWKSelector jwkSelector, SecurityContext context) throws KeySourceException {
        List<RsaKeyPair> keyPairs = this.keyPairRepository.findKeyPairs();
        List<JWK> result = new ArrayList<>(keyPairs.size());
        for (RsaKeyPair keyPair : keyPairs) {

            RSAKey rsaKey = new RSAKey.Builder(keyPair.getPublicKey())
                    .privateKey(keyPair.getPrivateKey())
                    .keyID(keyPair.getId())
                    .build();
            if (jwkSelector.getMatcher().matches(rsaKey)) {
                result.add(rsaKey);
            }
        }
        return result;
    }
}
